const btn = document.querySelector("#switch");
const calculateBtn = document.querySelector("#calculateBtn");
const messageWrap = document.querySelector("#message");

chrome.storage.sync.get("linkOpen", ({ linkOpen }) => {
  btn.checked = linkOpen;
});


calculateBtn.addEventListener("click", () => {
    const formula = document.querySelector("#formula").value;
     //只允许有'+'、'-'、'*'、'/'和括号'(',')'
     let reg = /^(?=.+\.*)[\d\s\(\)\*\/+\-\.]+$/;
     if(!reg.test(formula)) {//如果表达式不合法
         messageWrap.innerHTML = '<span>请输入合法的运算表达式!</span>'
         return;
     }else {//清空警告
        document.querySelector("#formula").setAttribute('value','')
        messageWrap.innerHTML = ''
     }
    let result = calculate(formula);
    console.log("result",result);
    document.querySelector("#result").innerHTML = result
  });


  function calculate(s) {
    console.log("s",typeof s);
    if(typeof s == 'string') {
        console.log("将字符串转换为数组");
        s = s.split('');
    }
   
    let stk = [];
    let num = 0;
    let dotNum = 0;
    let sign = '+';
    let dot = false
    while(s.length) {

        let c = s.shift();
        if(c -'0' >= 0 && c - '0' <= 9 && c !== ' ') {
            console.log("当前是数字",c,dot);
            if(dot) {
                console.log("dotNum");
                dotNum = 10*dotNum + Number(c);
                
            }else {
                num = 10 * num + Number(c);
            }
            
        }
        if(c === '.') {
            console.log("碰到.");
            dot = true;
            console.log("dot",dot);
        }

        if(c === '('){
            num = calculate(s);
        } 
        if((!(c -'0' >= 0 && c - '0' <= 9) && c !== ' ' && c !== '.') || s.length === 0) {
            console.log(num,dotNum);
            let allNum = dot ? Number( num+'.'+dotNum) : num;
            switch(sign) {
                case '+':stk.push(allNum) ;break;
                case '-':stk.push(-allNum) ;break;
                case '*':{
                    stk.push(stk.pop() * allNum);
                    break;
                }
                case '/':{
                    stk.push(stk.pop() / allNum );
                    break;
                }
            }
            num = 0;
            dotNum = 0;
            sign = c;
            dot = false;
        }
        if(c === ')') break;

    }
    //返回栈中总和
    return stk.reduce((p,n) => p + n)
    
}

// 刷新页面
function refreshPage() {
  window.location.reload();
}
